package module;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.MenuItem;

public class BtnSelectionAdapter extends SelectionAdapter {
	private AppAction appAction;
	private Class<? extends AppAction> ownerClass;

	public BtnSelectionAdapter() {
		appAction = new AppAction();
		ownerClass = appAction.getClass();
	}

	@Override
	public void widgetSelected(SelectionEvent e) {
		MenuItem nMenu = (MenuItem) e.widget;
		String actionName = nMenu.getData("action").toString();
		Object args = nMenu.getData("args");
		if (args != null) {
			invokeMethod(actionName, (Object[]) args);
		} else {
			invokeMethod(actionName);
		}

	}

	public void invokeMethod(String actionName) {
		Method method;
		try {
			method = ownerClass.getMethod(actionName);
			try {
				method.invoke(appAction);
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			}
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}
	}

	public void invokeMethod(String actionName, Object[] args) {
		Class<?>[] argsClass = new Class[args.length];
		for (int i = 0, j = args.length; i < j; i++) {
			argsClass[i] = args[i].getClass();
		}
		Method method;
		try {
			method = ownerClass.getMethod(actionName, argsClass);
			try {
				method.invoke(appAction, args);
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			}
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		}
	}

}
